package edu.uni.dormitory.controller;

import edu.uni.auth.bean.User;
import edu.uni.auth.service.AuthService;
import edu.uni.bean.Result;
import edu.uni.dormitory.bean.MaintenanceApply;
import edu.uni.dormitory.bean.MaintenanceEvaluation;
import edu.uni.dormitory.bean.RoomMaintenance;
import edu.uni.dormitory.globalbean.MaintenancePersonVo;
import edu.uni.dormitory.globalbean.MaintenanceVo;
import edu.uni.dormitory.globalbean.StudentBedVo;
import edu.uni.dormitory.service.AreaService;
import edu.uni.dormitory.service.MaintenanceService;
import edu.uni.dormitory.service.StudentBedService;
import edu.uni.example.config.ExampleConfig;
import edu.uni.userBaseInfo1.service.StudentService;
import edu.uni.userBaseInfo1.service.UserService;
import edu.uni.dormitory.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static edu.uni.bean.ResultType.Failed;
import static edu.uni.bean.ResultType.Success;

/**
 * @author 郑伟森
 * @create 2019.05.01
 * @function 宿舍报修
 */
@Api(description = "宿舍报修模块")
@RestController
@RequestMapping("json/dorm/maintenance")
public class MaintenanceController{
    @Autowired
    private MaintenanceService maintenanceService;
    @Autowired
    private ExampleConfig globalConfig;

    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;

    @Autowired
    private StudentBedService studentBedService;
    @Autowired
    private AreaService areaService;


    @Autowired
    private AuthService authService;
    /**
     * 通过主键获取某条报修记录
     */
    @ApiOperation("通过id获取某条维修记录")
    @GetMapping("{id}")
    public Result receiveMaintenanceById(@PathVariable("id")Long id,HttpSession session){
        System.out.println(id);

        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能获取的权限
            MaintenanceApply maintenanceApply=null;
            //学生
            if(isHasRole(roleList,"学生")){
                maintenanceApply = maintenanceService.selectMaintenanceApplyByIdWithSelf(id, Long.valueOf(loginId));
            }//宿管
            else if(isHasRole(roleList,"宿管")){
//                根据宿管id获取所管辖的宿舍区
                Long areaId = (Long) session.getAttribute("areaId");
                if(areaId == null){
                    areaId = areaService.selectAreaIdByEid(Long.parseLong(loginId)).getAreaId();
                }
                maintenanceApply = maintenanceService.selectMaintenanceApplyByIdWithHouseMaster(id, areaId);
            }//宿管中心
            else if(isHasRole(roleList,"宿管中心人员")){
                maintenanceApply = maintenanceService.selectMaintenanceApplyById(id);
            }//基建科
            else if(isHasRole(roleList,"基建科人员")) {
                maintenanceApply = maintenanceService.selectMaintenanceApplyById(id);
            }
            if(maintenanceApply != null){
                String applyId = String.valueOf(maintenanceApply.getId());
                Long studentId = maintenanceApply.getApplyPerson();
                String studentNo = studentService.selectById(studentId).getStuNo();
                String studentName = userService.selectUserById(studentId).getUserName();
                //根据学生id获取宿舍楼、宿舍
                StudentBedVo studentBedVo = studentBedService.selectStudentBedBySid(studentId);
                String areaName =studentBedVo.getAreaName();
                String filedName = String.valueOf(studentBedVo.getRoom());
                String applyDate = DateUtil.date2string(maintenanceApply.getDatetime());
                String reason = maintenanceApply.getDescription();
                String status = maintenanceService.selectMaintenanceStatusByApplyId(maintenanceApply.getId());
                MaintenanceEvaluation evaluation = maintenanceService.selectEvaluationByApplyId(id);
                MaintenanceVo maintenanceVo = new MaintenanceVo(applyId,studentName,studentNo,areaName,filedName,applyDate,reason,status,evaluation.getEvaluation());
                return Result.build(Success).appendData("list",new ArrayList<MaintenanceVo>(){{this.add(maintenanceVo);}});
            }
        //缓存
        return Result.build(Success);
    }
    /**
     * 获取维修记录
     */
    @ApiOperation("获取维修记录")
    @GetMapping("listAll")
    public Result getMaintenanceList(Long areaId,Integer status,HttpSession session){

        edu.uni.auth.bean.User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能获取的权限
            List<MaintenanceApply> maintenanceApplies = null;
            //学生
            if(isHasRole(roleList,"学生")){
                maintenanceApplies = maintenanceService.selectMaintenanceApplyPageWithSelf(Long.valueOf(loginId));
            }//宿管
            else if(isHasRole(roleList,"宿管")){
//                根据宿管id获取所管辖的宿舍区
                areaId = (Long) session.getAttribute("areaId");
                if(areaId == null){
                    areaId = areaService.selectAreaIdByEid(Long.parseLong(loginId)).getAreaId();
                }
                maintenanceApplies = maintenanceService.selectMaintenanceApplyPageByArea(areaId);
            }//宿管中心
            else if(isHasRole(roleList,"宿管中心人员")){
                maintenanceApplies = maintenanceService.selectMaintenanceApplyList();
//                maintenanceApplies = maintenanceService.selectMaintenanceApplyPageByArea(areaId);
            }//基建科
            else if(isHasRole(roleList,"基建科人员")){
                maintenanceApplies = maintenanceService.selectMaintenanceApplyList();
//                maintenanceApplies = maintenanceService.selectMaintenanceApplyPageByArea(areaId);
            }

            if(maintenanceApplies != null && maintenanceApplies.size() > 0){
                List<MaintenanceVo> maintenanceVoList = new ArrayList<>();
                for(MaintenanceApply m:maintenanceApplies){
                    String applyId = String.valueOf(m.getId());
                    String s = maintenanceService.selectMaintenanceStatusByApplyId(m.getId());
                    if(!judgeStatus(status,s,roleList)) continue;
                    Long studentId = m.getApplyPerson();
                    String studentNo = studentService.selectById(studentId).getStuNo();
                    String studentName = userService.selectUserById(studentId).getUserName();
                    //根据学生id获取宿舍楼、宿舍
                    StudentBedVo studentBedVo = studentBedService.selectStudentBedBySid(studentId);
                    String areaName =studentBedVo.getAreaName();
                    String filedName = String.valueOf(studentBedVo.getRoom());

                    String applyDate = DateUtil.date2string(m.getDatetime());
                    String reason = m.getDescription();
                    MaintenanceEvaluation maintenanceEvaluation = maintenanceService.selectEvaluationByApplyId(m.getId());
                    String evaluation = maintenanceEvaluation == null?null:maintenanceEvaluation.getEvaluation();
                    MaintenanceVo maintenanceVo = new MaintenanceVo(applyId,studentName,studentNo,areaName,filedName,applyDate,reason,s,evaluation);
                    maintenanceVoList.add(maintenanceVo);
                }
                return Result.build(Success).appendData("list", maintenanceVoList);
            }

        return Result.build(Failed);
    }
    /**
     * 学生报修
     */
    @PostMapping("")
    public Result insertMaintenance(@RequestBody MaintenanceApply maintenanceApply, HttpSession session){
        System.out.println(maintenanceApply);
        //获取登录人id、角色
        edu.uni.auth.bean.User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能申请的权限
            //学生
            if(isHasRole(roleList,"学生")){
                int i = maintenanceService.insertMaintenanceApply(maintenanceApply,Long.valueOf(loginId));
                if(i > 0){
                    return Result.build(Success);
                }
            }
            //其他人
        return Result.build(Success);
    }
    /**
     * 宿管、基建科审核报修
     */
    @PostMapping("{id}")
    public Result checkMaintenance(@PathVariable("id")Integer id,String agree, Long personId,HttpSession session){
        //获取登录人id、角色
        edu.uni.auth.bean.User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能申请的权限
            int i = 0;
            //宿管
            if(isHasRole(roleList,"宿管")) {
//                根据宿管id获取所管辖的宿舍区
                Long areaId = (Long) session.getAttribute("areaId");
                if(areaId == null){
                    areaId = areaService.selectAreaIdByEid(Long.parseLong(loginId)).getAreaId();
                }
                i = maintenanceService.updateMaintenanceApplyWithHouseMaster(Byte.valueOf(agree),areaId,Long.valueOf(loginId),Long.valueOf(id));
            }//宿管科
            else if(isHasRole(roleList,"基建科人员") && personId!=null){
                RoomMaintenance maintenance = new RoomMaintenance();
                maintenance.setMaintenanceDate(new Date());
                maintenance.setMaintenancePerson(personId);
                i = maintenanceService.updateMaintenanceApplyWithInfrastructureSection(maintenance,Long.valueOf(loginId) ,Long.valueOf(id));
            }
            //其他人
            if(i > 0){
                return Result.build(Success);
            }
        return Result.build(Failed);
    }
    /**
     * 报修人评价维修情况
     */
    @PostMapping("{id}/evaluation")
    public Result evaluationMaintenance(@PathVariable("id")Integer id, String evaluation,HttpSession session){
        //获取登录人id、角色
        edu.uni.auth.bean.User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();

        //根据身份判断是否有能申请的权限
            int i = 0;
            //学生
            if(isHasRole(roleList,"学生")) {
                MaintenanceEvaluation maintenanceEvaluation = new MaintenanceEvaluation();
                maintenanceEvaluation.setEvaluation(evaluation);
                i = maintenanceService.insertMaintenanceEvaluation(Long.valueOf(id),maintenanceEvaluation,Long.valueOf(loginId));
            }
            //其他人
            if(i > 0){
                return Result.build(Success);
            }
        return Result.build(Failed);
    }
    @GetMapping("maintenancePerson")
    public Result getMaintenancePerson(){
        MaintenancePersonVo person1 = new MaintenancePersonVo("5","维修人员1");
        MaintenancePersonVo person2 = new MaintenancePersonVo("4","维修人员2");
        MaintenancePersonVo person3 = new MaintenancePersonVo("6","维修人员3");
        List<MaintenancePersonVo> users = new ArrayList<>();
        users.add(person1);
        users.add(person2);
        users.add(person3);
        return Result.build(Success).appendData("maintenancePerson",users);
    }
    private boolean judgeStatus(Integer status,String s,List<String> roleList){
        if(!"不同意".equals(s) && isHasRole(roleList,"宿管")){
            if(0 == status && "宿管确认中".equals(s)) return true;
            if(1 == status) {
                if( "基建科派人中".equals(s)||"维修完成待评价".equals(s)|| "已完成".equals(s)){
                    return true;
                }
            }
        }else if(!"不同意".equals(s) && isHasRole(roleList,"基建科人员")){
            if(0 == status && "基建科派人中".equals(s)) return true;
            if(1 == status) {
                if("维修完成待评价".equals(s) || "已完成".equals(s)) {
                    return true;
                }
            }
        }else if(isHasRole(roleList,"学生")){
            //0--待评价
            if( 0 == status && "维修完成待评价".equals(s)) return true;
            //1--所有
            if(1 == status) {
                return true;
            }
            //2-不是待评价
            if(2 == status &&  !"维修完成待评价".equals(s)) {
                return true;
            }
        }
        return false;
    }

    private boolean isHasRole(List<String> roleList, String role) {
        for(String r:roleList){
            if(r.equals(role)){
                return true;
            }
        }
        return false;
    }
}
